package com.company.aop.dao.impl;


import com.company.aop.dao.IAccountDao;
import com.company.aop.pojo.Account;
import com.company.util.ConnectionUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @date : 2022/3/25 21:33
 * 数据访问层实现类
 */

@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

//    @Resource
//    private QueryRunner runner;

    private QueryRunner runner;

    private ConnectionUtils connectionUtils;

    @Autowired
    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

    @Autowired
    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    @Override
    public int saveAccount(Account account) {
        try {
            return runner.update(connectionUtils.getThreadConnection(),
                    "insert into account(id,name,money)values(?,?,?)",
                    account.getId(),
                    account.getName(),
                    account.getMoney());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account selectById(Integer id) {
        try {
            return runner.query(connectionUtils.getThreadConnection(),
                    "select * from account where id = ? ",
                    new BeanHandler<>(Account.class), id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Account> getAll() {
        try {
            return runner.query(connectionUtils.getThreadConnection(),
                    "select * from account",
                    new BeanListHandler<>(Account.class));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int updateAccount(Account account) {
        try {
            return runner.update(connectionUtils.getThreadConnection(),
                    "update account set name=?,money=? where id=?",
                    account.getName(),
                    account.getMoney(),
                    account.getId());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int deleteAccount(Integer id) {
        try {
            return runner.update(connectionUtils.getThreadConnection(),
                    "delete from account where id=?", id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
